const multer = require('multer');
const { BosClient } = require('bce-sdk-js');
const { BadRequest } = require('http-errors');

const config = {
  endpoint: process.env.BAIDU_BOS_ENDPOINT,
  credentials: {
    ak: process.env.BAIDU_BOS_AK,
    sk: process.env.BAIDU_BOS_SK,
  },
  bucket: process.env.BAIDU_BOS_BUCKET,
};

const client = new BosClient(config);
// multer 配置信息
const upload = multer({
  storage: multer.memoryStorage(),
  fileFilter: function (req, file, cb) {
    // 只允许上传图片
    const fileType = file.mimetype.split('/')[0];
    const isImage = fileType === 'image';

    if (!isImage) {
      return cb(new BadRequest('只允许上传图片。'));
    }

    cb(null, true);
  }
});

// 把文件传到 BOS
async function uploadToBOS(buffer, filename) {
  const bosKey = `uploads/${filename}`;
  // 这里用 putObject 而不是 putObjectFromFile
  await client.putObject(config.bucket, bosKey, buffer);
  return `${config.endpoint.replace(/^http:/, 'https:')}/${config.bucket}/${bosKey}`;
}

const fileSizeLimits = (req, res, next) => {
  const contentLength = parseInt(req.headers['content-length']);
  // 限制上传文件的大小为：5MB
  if (contentLength > 5 * 1024 * 1024) {
    return next(new BadRequest('文件大小不能超过5MB'));
  }
  next();
};

/**
 * 单文件上传，指定表单字段名为 file
 * @param req
 * @param res
 * @param next
 */
const singleFileUpload = (req, res, next) => {
  // 检查文件大小是否超出限制
  fileSizeLimits(req, res, (err) => {
    if (err) return next(err);
    upload.single('file')(req, res, next);
  });
};


module.exports = { singleFileUpload, uploadToBOS, client, config };